import { defineStore } from 'pinia';
import { io } from 'socket.io-client';
import { useUserStore } from './UserStore';

// 自定义事件总线
const eventBus = {
  listeners: {},
  on(event, callback) {
    if (!this.listeners[event]) {
      this.listeners[event] = [];
    }
    this.listeners[event].push(callback);
  },
  off(event, callback) {
    if (this.listeners[event]) {
      this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);
    }
  },
  emit(event, payload) {
    if (this.listeners[event]) {
      this.listeners[event].forEach(cb => cb(payload));
    }
  }
};

export const useWebSocketStore = defineStore('websocket', {
  state: () => ({
    socket: null,
    isConnected: false,
    reconnectAttempts: 0,
    maxReconnectAttempts: 5,
    messageQueue: [],
  }),
  actions: {
    connect() {
      const userStore = useUserStore();

      if (this.socket && this.isConnected) return;

      const token = userStore.token;
      const userId = userStore.curUser?.id || null;
      const role = userStore.curUser?.role || 'guest';

      this.socket = io('http://localhost:5000', {
        auth: {
          token,
          userId,
          role,
          reconnection: true,
          reconnectionAttempts: Infinity,
          randomizationFactor: 0.5,
        },
        transports: ['websocket'],
      });

      this.socket.on('connect', () => {
        console.log('[WebSocket] 已连接');
        this.isConnected = true;
        this.reconnectAttempts = 0;
        this.flushMessageQueue();
        this.emit('user:connected', { userId, role });
      });

      this.socket.on('disconnect', (reason) => {
        console.log('[WebSocket] 断开连接:', reason);
        this.isConnected = false;
      });

      this.socket.on('connect_error', (error) => {
        console.error('[WebSocket] 连接错误:', error.message);
        this.handleReconnect();
      });

      // 监听后端消息并转发给 eventBus
      this.socket.on('server:order-updated', (payload) => {
        eventBus.emit('server:order-updated', payload);
      });

      this.socket.on('server:room-status-updated', (payload) => {
        eventBus.emit('server:room-status-updated', payload);
      });

      this.socket.on('server:cancel-request-submitted', (payload) => {
        eventBus.emit('server:cancel-request-submitted', payload);
      });

      this.socket.on('server:user-created', (payload) => {
        eventBus.emit('server:user-created', payload);
      });

      this.socket.on('server:room-deleted', (payload) => {
        eventBus.emit('server:room-deleted', payload);
      });

      this.socket.onAny((event, ...args) => {
        console.log(`[WebSocket] 收到未知事件: ${event}`, args);
      });
    },

    send(event, data) {
      if (this.isConnected) {
        this.socket.emit(event, data);
      } else {
        console.warn('WebSocket 未连接，消息已暂存');
        this.messageQueue.push({ event, data });
      }
    },

    disconnect() {
      if (this.socket) {
        this.socket.disconnect();
        this.isConnected = false;
      }
    },

    handleReconnect() {
      if (this.reconnectAttempts < this.maxReconnectAttempts) {
        setTimeout(() => {
          this.reconnectAttempts++;
          console.log(`第 ${this.reconnectAttempts} 次重连...`);
          this.connect();
        }, Math.min(1000 * Math.pow(2, this.reconnectAttempts), 10000));
      } else {
        console.warn('达到最大重试次数，停止连接');
      }
    },

    flushMessageQueue() {
      this.messageQueue.forEach(({ event, data }) => {
        this.socket.emit(event, data);
      });
      this.messageQueue = [];
    },

    // ✅ 使用 eventBus 实现 on/off/emit
    on(event, callback) {
      eventBus.on(event, callback);
    },

    off(event, callback) {
      eventBus.off(event, callback);
    },

    emit(event, data) {
      eventBus.emit(event, data);
    },
  },
});